package com.wudl.govern.service.impl;

import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wudl.govern.config.DataDictUtils;
import com.wudl.govern.config.DispatchrUtils;
import com.wudl.govern.constant.DispatchConstant;
import com.wudl.govern.domain.ControlRule;
import com.wudl.govern.domain.ControlTask;
import com.wudl.govern.domain.TaskRule;
import com.wudl.govern.mapper.ControlRuleMapper;
import com.wudl.govern.mapper.ControlTaskMapper;
import com.wudl.govern.mapper.ReportDetailMapper;
import com.wudl.govern.mapper.TaskRuleMapper;
import com.wudl.govern.service.ControlTaskService;
import com.wudl.govern.utils.RestTemplateUtils;
import com.wudl.govern.utils.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.web.client.RestTemplate;


import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：wudl
 * @date ：Created in 2022-04-05 13:19
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Service
@Slf4j
public class ControlTaskServiceImpl implements ControlTaskService {

    private RestTemplate restTemplate = new RestTemplate();
    private final String MANUAL = "101001";
    private final String DISPATCH = "101002";
    private final int SUCCESS = 100;
    private final String JOB_STATE_ON = "1";

    @Autowired
    private ControlTaskMapper controlTaskMapper;



    @Autowired
    private TaskRuleMapper taskRuleMapper;

    @Autowired
    private ControlRuleMapper controlRuleMapper;

    @Resource
    private ReportDetailMapper reportDetailMapper;
    @Resource
    private DataDictUtils dataDictUtils;


    /**
     * 按条件分页查询
     *
     * @param controlTask
     * @return
     */
    @Override
    public  List<Map<String, Object>>  selectPage(ControlTask controlTask) {
        try {
            log.info("查询page传参:{}", JSON.toJSONString(controlTask));
            if (StringUtils.isNotBlank(controlTask.getTaskName())) {
                controlTask.setTaskName("名称");
            }

            List dbIds = new ArrayList();
            //权限控制
            if(controlTask.getTableId() == null || controlTask.getTableId() < 0){
                //得到用户市所属部门及子部门，如果用户为系统管理员或质量负责人，则得到的部门为空
            //    List<Integer> deptList = dataDictUtils.checkingRoles(MetaMsgUtil.PERMISSION_TYPE_TWO);
                List<Integer> deptList  = Arrays.asList(1,5,7,8);
                if(deptList != null && deptList.size() > 0){
                    //根据部门得到数据源id集合(如果部门id为空，表示可以查看所有)
                 //   dbIds = dataDictUtils.getSourceIdByDeptId(deptList);
                    controlTask.setSourceIds(dbIds);
                }
                //有部门权限，但是数据源却为空，表示无法查看数据
                if(deptList != null && deptList.size() > 0 && (dbIds == null || dbIds.size() <= 0)){
                    return null;
                }
            }else{
                List tabId = new ArrayList();
                tabId.add(controlTask.getTableId());
                controlTask.setTableIds(tabId);
            }

            PageHelper.startPage(controlTask.getPageNumber() == null ? 1 : Integer.parseInt(controlTask.getPageNumber().toString())
                    , controlTask.getPageSize() == null ? 10 : Integer.parseInt(controlTask.getPageSize().toString()));
            List<Map<String, Object>> controlTaskList = controlTaskMapper.selectPage(controlTask);
            if(controlTaskList == null || controlTaskList.isEmpty()){
                return controlTaskList;
            }
            Page page = (Page) controlTaskList;
            if(controlTaskList == null || controlTaskList.isEmpty()){
                return controlTaskList;
            }
//            List<Map<String, Object>> taskList = userUtils.fillMap(page.getResult());
            List<Map<String, Object>> taskList = new ArrayList<>();
            //获取所有的jobId
            String jobIds = taskList.stream().map(task -> task.get("jobId").toString()).reduce((a, b) -> a + "," + b).orElse("");
            if (StringUtils.isNotBlank(jobIds)) {
                //调用接口查询任务信息
                Map resultInfo = getJobInfo(jobIds);
                if(resultInfo != null){
                    int codeInfo = Integer.parseInt(resultInfo.get("code").toString());
                    if (codeInfo != SUCCESS) {
                        return null;
                    }
                    Map<String, Map<String, String>> jobInfoMap = (Map<String, Map<String, String>>) resultInfo.get("data");
                    taskList = taskList.stream().map(task -> {
                        task.put("runNum", jobInfoMap.get("exeNumberMap").get(task.get("jobId").toString()));
                        task.put("runState", jobInfoMap.get("statusMap").get(task.get("jobId").toString()));
                        return task;
                    }).collect(Collectors.toList());
                }
            }
            log.info("result: {}", taskList);

            //获取数据源id集合
            List<Integer> ids = taskList.stream().map(data -> Integer.parseInt(data.get("sourceId").toString())).collect(Collectors.toList());
            //调用接口获取数据
//            Map dbSourceResult = commonFiegn.getSourceByIds(ids);
            Map dbSourceResult = new HashMap();
            log.info("按部门id查询部门详情,deptResult : " + dbSourceResult);

            int code = Integer.parseInt(dbSourceResult.get("code").toString());
            if (code != SUCCESS) {
                return null;
            }
            List<Map> dataList = (List<Map>) dbSourceResult.get("data");
            List<Map> result = taskList.stream().map(data -> {
                Optional<Map> dbSourceOptional = dataList.stream().filter(d -> d.get("dbSourceId").equals(data.get("sourceId"))).findAny();
                if (dbSourceOptional.isPresent()) {
                    data.put("dbName", dbSourceOptional.get().get("dbSourceName"));
                }
                return data;
            }).collect(Collectors.toList());
            return null;

        } catch (Exception e) {
            log.error("##### 分页查询监控任务异常 ##### error={}", e);
            return null;
        }
    }

    /**
     * 修改一条记录
     *
     * @param record
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object updateOne(ControlTask record, BindingResult bindingResult, UserInfo userInfo) {
        try {
            log.info("ControlTask {}", JSON.toJSON(record).toString());
            if (bindingResult.hasErrors()) {
                log.info("校验不合法：{}", JSON.toJSON(bindingResult.getFieldErrors()).toString());
                Optional<String> errors = bindingResult.getAllErrors().stream().map(error -> error.getDefaultMessage()).reduce((a, b) -> a + "," + b);
                return null;
            }
            //查询corn
            String corn = controlTaskMapper.selectCorn(record.getId());
            //判断任务名是否重复
            List<Map<String, Object>> taskNameMap = controlTaskMapper.selectByName(record.getTaskName());
            Optional<List<Map<String, Object>>> optionalMap = Optional.of(taskNameMap);

            if (optionalMap.isPresent() && optionalMap.get().size()>0 && optionalMap.get().stream().anyMatch(a -> record.getId() != Integer.parseInt(a.get("id").toString()))) {
                log.info("任务{}已存在", record.getTaskName());
                return null;
            }

            String jobId = controlTaskMapper.selectTaskJobId(record.getId());

            //调用接口查询任务信息
            Map resultInfo = getJobInfo(jobId);
            int codeInfo = 0;
            if(null != resultInfo && resultInfo.containsKey("code")){
                codeInfo = Integer.parseInt(resultInfo.get("code").toString());
            }
            if (codeInfo != SUCCESS) {
                return null;
            }
            Map<String, Map<String, String>> jobInfoMap = (Map<String, Map<String, String>>) resultInfo.get("data");
            if (jobInfoMap == null || jobInfoMap.isEmpty()) {
                return null;
            }
            String jobState = jobInfoMap.get("statusMap").get(jobId);
            //校验是否是执行状态
            if (jobState.equals(JOB_STATE_ON)) {
                log.info("#####任务运行中，不能修改#####");
                return null;
            }


            //获取ruleid集合
            List<Integer> ids = record.getControlRules().stream().distinct().map(ControlRule::getId).collect(Collectors.toList());
            //获取tableId集合
            List<Integer> tableIds = controlRuleMapper.findTableIds(ids);
            //判断任务中规则的表id是否相同
            if (tableIds.size() != 1) {
                return null;
            }
            //获取dataSource
            Map resultDs = getDbSource(record.getSourceId());

            //添加数据源
            int codeDs = Integer.parseInt(resultDs.get("code").toString());
            if (codeDs != SUCCESS) {
                return null;
            }
            if(null!= resultDs.get("data") && JSONArray.parseArray(JSON.toJSONString(resultDs.get("data"))).size()>0){
                Map dbSource = ((List<Map>) resultDs.get("data")).get(0);
                record.setDbDriver(dbSource.get("dbDriver").toString());
                record.setDbHost(dbSource.get("host").toString());
                record.setDbName(dbSource.get("dbSourceName").toString());
                record.setDbType(dbSource.get("dbType").toString());
                record.setJdbcParam(dbSource.get("jdbcParam") + "");
            }

            //设置数据状态
            record.setDataState(1);
            //TODO
//            record.setUppUser(491 + "");
            record.setUppUser( "user001");
            record.setUppDate(new Date());


            //获取列
            Map pkResult = getPkColumn(record.getTableId());
            int pkCode = Integer.parseInt(pkResult.get("code").toString());
            if (pkCode != SUCCESS) {
                return null;
            }
            List<Map<String, Object>> columnList = (List<Map<String, Object>>) (pkResult.get("data"));
            if (columnList != null && !columnList.isEmpty()) {
                record.setTablePkColumn(columnList.get(0).get("columnName").toString());
            }

            //删除rule和task的关系
            if (taskRuleMapper.deleteRelation(record.getId()) <= 0) {
                log.info("###删除rule和task的关系失败###");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }
            //添加task和rule的关系
            if (addTaskRuleRelation(record) <= 0) {
                log.info("###添加rule和task的关系失败###");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }
            if (record.getExecutionWay().equals(MANUAL)) {
                record.setCronDescribe("1 1 1 1 1 ?");
            }
            //修改task
            if (controlTaskMapper.updateByPrimaryKeySelective(record) <= 0) {
                log.info("###修改task失败###");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }


            //如果corn修改了，调用接口更新调度

            if (!record.getCronDescribe().equals(corn) && record.getExecutionWay().equals(DISPATCH)) {

                log.info("####corn表达式修改了#####");
                //调用接口修改任务
                //TODO email
                Map result = DispatchrUtils.updateTask(jointParams(record, "gEmail"), restTemplate);
                int code = Integer.parseInt(result.get("code").toString());
                if (code != SUCCESS) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.info("###修改调度任务失败###");
                    return null;
                }
            }


            log.info("##### 修改成功 #####");
            return "Success";
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("##### 修改监控任务异常 ##### error={}", e);
            return null;
        }
    }

    /**
     * 删除一条质量监控任务
     * author ：qunan
     * date ：2018/12/3
     *
     * @param taskId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteOne(Integer taskId) {
        try {
            //判断任务id是否为空
            if (taskId == null) {
                log.info("####任务id不能为空###");
                return null;
            }
            //查询运行时状态
            String jobId = controlTaskMapper.selectTaskJobId(taskId);
            //调用接口查询任务信息
            Map resultInfo = getJobInfo(jobId);
            int codeInfo = 0;
            if(null != resultInfo){
                codeInfo = Integer.parseInt(resultInfo.get("code").toString());
            }
            if (codeInfo != SUCCESS) {
                return null;
            }
            Map<String, Map<String, String>> jobInfoMap = (Map<String, Map<String, String>>) resultInfo.get("data");
            //校验是否是执行状态
            if (jobInfoMap.get("statusMap").get(jobId).equals(JOB_STATE_ON)) {
                log.info("#####任务运行中，不能修改#####");
                return null;
            }
            //删除调度任务
//            Map result = DispatchrUtils.removeTask(Integer.valueOf(controlTaskMapper.selectTaskJobId(taskId)), restTemplate);
            Map result = new HashMap();
            int code = Integer.parseInt(result.get("code").toString());
            if (code != SUCCESS) {
                log.info("####删除调度任务失败！###");
                return null;
            }
            //删除任务
            if (controlTaskMapper.deleteOne(taskId) <= 0) {
                log.info("#####删除任务异常#####");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }
//            //删除任务与规则
//            if (taskRuleMapper.deleteById(taskId) <= 0) {
//                LOGGER.info("删除任务与规则关系异常!");
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return ResultUtil.error(ResultEnum.DB_DELETE_FAIL.getCode(), ResultEnum.DB_DELETE_FAIL.getMsg());
//            }
            log.info("#####删除成功#####");
            return "Success";
        } catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("##### 逻辑删除监控任务异常 ##### error={}", e);
            return null;
        }

    }


    /**
     * 新增一条记录
     * author ：qunan
     * date ：2018/12/3
     *
     * @param record
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object insertOne(ControlTask record, BindingResult bindingResult, UserInfo userInfo) {
        try {
            log.info("ControlTask {}", JSON.toJSON(record).toString());
            if (bindingResult.hasErrors()) {
                log.info("校验不合法：{}", JSON.toJSON(bindingResult.getFieldErrors()).toString());
                Optional<String> errors = bindingResult.getAllErrors().stream().map(error -> error.getDefaultMessage()).reduce((a, b) -> a + "," + b);
                return null;
            }
            //判断任务名是否重复
            List<Map<String, Object>> taskName = controlTaskMapper.selectByName(record.getTaskName());
            Optional<List<Map<String, Object>>> optionalMap = Optional.of(taskName);
            if (optionalMap.isPresent() && optionalMap.get().size()>0) {
                log.info("任务{}已存在", record.getTaskName());
                return null;
            }

            if (record.getExecutionWay().equals(MANUAL)) {
                //设置一次启动的调度任务的corn
                record.setCronDescribe("1 1 1 1 1 ?");
            } else {
                //校验corn表达式是否为空
                if (StringUtils.isBlank(record.getCronDescribe())) {
                    return null;
                }
            }
            //获取ruleid集合
            List<Integer> ids = record.getControlRules().stream().distinct().map(ControlRule::getId).collect(Collectors.toList());
            //查规则id集合的表id集合
            List<Integer> tableIds = controlRuleMapper.findTableIds(ids);
            //判断任务中规则的表id是否相同
            if (tableIds.size() != 1) {
                return null;
            }

            Map resultDs = getDbSource(record.getSourceId());

            //添加数据源
            int codeDs = Integer.parseInt(resultDs.get("code").toString());
            if (codeDs != SUCCESS) {
                return null;
            }
            Map dbSource = ((List<Map>) resultDs.get("data")).get(0);
            record.setDbDriver(dbSource.get("dbDriver") == null ? "" : dbSource.get("dbDriver").toString());
            record.setDbHost(dbSource.get("host") == null ? "" : dbSource.get("host").toString());
            record.setDbPort(dbSource.get("port") == null ? 3306 : Integer.parseInt(dbSource.get("port").toString()));
            record.setDbName(dbSource.get("dbSourceName") == null ? "" : dbSource.get("dbSourceName").toString());
            record.setDbType(dbSource.get("dbType") == null ? "" : dbSource.get("dbType").toString());
            record.setJdbcParam(dbSource.get("jdbcParam") == null ? "" : dbSource.get("jdbcParam").toString());
//            record.setPassword(dbSource.get("password") == null ? "" : dbSource.get("password").toString());
            //TODO
            record.setCreateDate(new Date());
//            record.setCreateUser(101 + "");
            record.setCreateUser("admin");
            record.setDataState(1);
            //获取列
            Map pkResult = getPkColumn(record.getTableId());
            int pkCode = Integer.parseInt(pkResult.get("code").toString());
            if (pkCode != SUCCESS) {
                return null;
            }
            List<Map<String, Object>> columnList = (List<Map<String, Object>>) (pkResult.get("data"));
            if (columnList != null && !columnList.isEmpty()) {
                record.setTablePkColumn(columnList.get(0).get("columnName").toString());
            }

            //校验执行方式
            //TODO email
            Map result = DispatchrUtils.addTask(jointParams(record, "getEmail"), restTemplate);
            int code = Integer.parseInt(result.get("code").toString());
            if (code != SUCCESS) {
                return null;
            }
            int jobId = Integer.parseInt(result.get("data").toString());

            log.info("#### jobId: {} # ###", jobId);
            if (jobId < 0) {
                return null;
            }

            //设置jobId
            record.setRunJobId(jobId + "");

            //新增调度任务
            if (controlTaskMapper.insertSelective(record) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }
            //新增rule和task的关系
            if (addTaskRuleRelation(record) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }


            return "success";


        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("##### 添加监控任务异常 ##### error={}", e);
            return null;
        }
    }

    /**
     * 拼接调度任务参数
     *
     * @param record
     * @return
     */
    private Map<String, Object> jointParams(ControlTask record, String email) {
        Map<String, Object> params = new HashMap<>(20);
        params.put("id", record.getRunJobId());
        params.put("jobGroup", DispatchConstant.JOB_GROUP);
        params.put("jobCron", record.getCronDescribe());
        params.put("jobDesc", record.getTaskDescribe()==null?"":record.getTaskDescribe());
        //TODO
//        params.put("author", 101);
//        params.put("author", userUtils.getUserInfo(Integer.parseInt(record.getCreateUser())).getUsername());
        params.put("alarmEmail", email == null ? "" : email);
        params.put("executorRouteStrategy", DispatchConstant.EXECUTOR_ROUTE_STRATEGY);
        params.put("executorHandler", DispatchConstant.EXECUTOR_HANDLER);
        Map<String, Object> executorParam = new HashMap<>(20);
        executorParam.put("packageName", DispatchConstant.PACKAGE_NAME_);
        executorParam.put("serviceName", DispatchConstant.SERVICE_NAME_);
        executorParam.put("methodName", DispatchConstant.METHOD_NAME_);
        Map<String, Object> param = new HashMap<>(1);
        param.put("type", 1);
        param.put("jobId", record.getRunJobId());
        executorParam.put("param", param);

        params.put("executorParam", JSON.toJSON(executorParam).toString());

        params.put("executorBlockStrategy", DispatchConstant.EXECUTOR_BLOCK_STRATEGY);
        params.put("executorTimeout", DispatchConstant.EXECUTOR_TIMEOUT);
        params.put("executorFailRetryCount", DispatchConstant.EXECUTOR_FAIL_RETRY_COUNT);
        params.put("childJobId", DispatchConstant.CHILD_JOB_ID);
        params.put("glueType", DispatchConstant.GLUE_TYPE);
        log.info("executorParam :{}", JSON.toJSON(params).toString());
        return params;
    }

    /**
     * 建立rule和task的关系
     *
     * @param record
     * @return
     */
    private int addTaskRuleRelation(ControlTask record) {
        Set<ControlRule> controlRules = record.getControlRules().stream()
                .distinct()
                .filter(cr -> cr.getId() != null)
                .collect(Collectors.toSet());

        if (controlRules != null && controlRules.size() > 0) {
            List<TaskRule> tontrolRulesList = new LinkedList<>();
            for (ControlRule controlRule : controlRules) {

                TaskRule taskRule = new TaskRule();
                taskRule.setTaskId(record.getId());
                taskRule.setRuleId(controlRule.getId());
                taskRule.setCreateDate(new Date());
                taskRule.setDataType(controlRule.getDataType());
                tontrolRulesList.add(taskRule);

            }
            return taskRuleMapper.addRelation(tontrolRulesList);
        }

        return 0;
    }

    /**
     * 根据id查询一条数据
     * author ：qunan
     * date ：2018/12/3
     *
     * @param taskId
     * @return
     */
    @Override
    public ControlTask selectOne(Integer taskId) {
        try {
            log.info("taskId: {}", taskId);
            if (taskId == null) {
                return null;
            }
            //查询质量监控任务
            ControlTask controlTask = controlTaskMapper.selectByPrimaryKey(taskId);
            //ids 规则id集合
            List<Integer> ids = taskRuleMapper.selectRuleTaskList(taskId);
            if (ids == null || ids.size() <= 0) {
                return null;
            }
            if (controlTask.getExecutionWay().equals(MANUAL)) {
                //设置corn
                controlTask.setCronDescribe("");
            }
            //把规则集合加入监控任务中
            controlTask.setControlRules(controlRuleMapper.selectByIds(ids));

            return controlTask;

        } catch (Exception e) {
            log.error("##### 查找任务异常异常 ##### error={}", e);
            return  null;
        }
    }

    @Override
    public Object startTask(Integer taskId) {
        try {
            log.info("taskId : {}", taskId);

            if (taskId == null) {
                log.info("##taskId为空##");
                return null;
            }

            //获取jobId
            String jobIdStr = controlTaskMapper.selectTaskJobId(taskId);
            if(jobIdStr == null){
                return null;
            }
            int jobId = Integer.parseInt(jobIdStr);
            log.info("jobId: {}", jobId);

            switch (controlTaskMapper.selectExecutionWay(taskId)) {
                //单次执行
                case MANUAL:
                    Map<String, Object> params = new HashMap<>(2);
                    params.put("jobId", jobId);

                    log.info("手动执行");
                    Map result = DispatchrUtils.singleTask(params, restTemplate);
                    int code = Integer.parseInt(result.get("code").toString());
                    if (code != SUCCESS) {
                        log.info("单次启动失败");

                        return result.get("message").toString();
                    }
                    return "success";
                case DISPATCH:
                    Map results = DispatchrUtils.onTask(jobId, restTemplate);
                    int codeState = Integer.parseInt(results.get("code").toString());
                    if (codeState != SUCCESS) {
                        log.info("调度启动失败");

                        return null;
                    }
                    return "success";
                default:
                    log.info("执行方式的值输入不合法");
                    return "执行方式的值输入不合法";
            }
        } catch (Exception e) {
            log.error("##### 开启任务异常异常 ##### error={}", e);
            return "开启任务异常异常";
        }
    }

    @Override
    public String pauseTask(Integer taskId) {
        try {

            int jobDd = Integer.parseInt(controlTaskMapper.selectTaskJobId(taskId));
            Map result = DispatchrUtils.offTask(jobDd, restTemplate);
            int code = Integer.parseInt(result.get("code").toString());
            if (code != SUCCESS) {
                log.info("###关闭调度任务失败###");
                return "关闭调度任务失败" ;
            }

            return "success";
        } catch (Exception e) {
            log.error("##### 暂停任务异常异常 ##### error={}", e);
            return "暂停任务异常异常";
        }
    }


    @Override
    public Map selectTaskRecord(Map<String, Object> params) {
        try {
            log.info("params : {}", params);
            params.put("type",1);
//            Map executeLogger = DispatchrUtils.selectExecuteLogger(params, restTemplate);
            Map executeLogger = new HashMap();
            int code = (int) executeLogger.get("code");
            if (code != SUCCESS) {
                return null;
            }
            Optional<Map> dataOption = Optional.of((Map) executeLogger.get("data"));
            if (!dataOption.isPresent()) {
                return null;
            }
            Map map = dataOption.get();
            return map;
        } catch (Exception e) {
            log.error("##### 查询任务状态异常异常 ##### error={}", e);
            return null;
        }
    }

    /***
     * 查询执行任务信息
     * @param jobId              jobId
     * @return
     */
    @Override
    public Map<String, Object> selectTaskInfo(String jobId) {
        Map<String, Object> map = controlTaskMapper.selectTaskInfo(jobId);
        List<Map<String, String>> list = controlTaskMapper.selectRuleList(jobId);
        if (map != null) {
            map.put("ruleList", list);
            return map;
        } else {
            return null;
        }
    }

    /***
     * 查询质量概览
     * @param param
     * @return
     */
    @Override
    public Object selectQualityOverview(JSONObject param) {
        List results = new ArrayList();
        List deptIds = new ArrayList();
        //过去七天(默认查询过去七天的数据)
        List createDates = StringHelper.PastDates(7);
        String dataType = "\"%Y-%m-%d\"";

        if(param.containsKey("deptIds") && param.getJSONArray("deptIds")!=null){
            deptIds = param.getJSONArray("deptIds");
        }
        if(param.containsKey("trend") && !StringHelper.isEmpty(param.getString("trend"))){
            String trend = param.getString("trend");
            if(trend.equals("1")){
                //过去七天(默认查询过去七天的数据)
                createDates = StringHelper.PastDates(7);
                dataType = "\"%Y-%m-%d\"";
            }else if(trend.equals("2")){
                //过去三十天
                createDates = StringHelper.PastDates(30);
                dataType = "\"%Y-%m-%d\"";
            }else if(trend.equals("3")){
                //过去三个月
                createDates = StringHelper.PastMonths(3);
                dataType = "\"%Y-%m\"";
            }else if(trend.equals("4")){
                //过去六个月
                createDates = StringHelper.PastMonths(6);
                dataType = "\"%Y-%m\"";
            }else if(trend.equals("5")){
                //过去一年
                createDates = StringHelper.PastYears(1);
                dataType = "\"%Y-%m\"";
            }
        }
        try {
            Collections.reverse(createDates);
            if(deptIds!=null && deptIds.size()>0){
//                String url = FileHelpper.map.get("service.common") + FileHelpper.map.get("dept.getDeptByIds");
                JSONObject ids = new JSONObject();
                ids.put("ids",deptIds);
//                LOGGER.info("接口请求地址:" + url);
//                String str = HttpUtil.requestUrl(url,JSON.toJSONString(ids));

//                String str = JSON.toJSONString(commonFiegn.getDeptByIds(ids));
                String str = "";
                log.info("接口返回参数:" + str);
                if(StringHelper.isEmpty(str)) {
                    log.info( "服务器异常！");
                    return null;
                }else{
                    JSONObject result = JSON.parseObject(str);
                    if(result.getIntValue("code")!=100 || result.getJSONArray("data")==null){
                        return str;
                    }else{
                        JSONArray data = result.getJSONArray("data");
                        for (int i = 0; i < data.size(); i++){
                            JSONObject deptObj = result.getJSONArray("data").getJSONObject(i);
                            Map<String,Object> dept = new HashMap<>();
                            String deptId = deptObj.getString("id");
                            dept.put("dept_id",deptId);
                            dept.put("deptId",deptObj.get("deptName"));
                            List<Map<String,Object>> reportDetail = reportDetailMapper.selectQualityOverview(deptId,createDates,dataType);
                            if(reportDetail != null && reportDetail.size()>0){
                                dept.put("reportDetail",reportDetail);
                                results.add(dept);
                            }
                        }
                    }
                }
            }else{
                //默认统计所有部门的近七天质量报告趋势
                List<Map<String,Object>> deptList = reportDetailMapper.selectDeptIdList();
                for(int i = 0; i < deptList.size(); i++){
                    Map<String,Object> dept = deptList.get(i);
                    String deptId = dept.get("dept_id").toString();
                    List<Map<String,Object>> reportDetail = reportDetailMapper.selectQualityOverview(deptId,createDates,dataType);
                    if(reportDetail != null && reportDetail.size()>0){
                        dept.put("reportDetail",reportDetail);
                        results.add(dept);
                    }
                }
            }

            Map<String,Object> result = new HashMap<>();
            //时间数组
            result.put("dateTime",createDates);
            result.put("results",results);
            return result;
        } catch (Exception e) {
            log.error("##### 查询任务状态异常异常 ##### error={}", e);
            return null;
        }
    }


    /**
     * 通过id得到数据源
     *
     * @param dbSourceId 数据源id
     * @return
     */
    private Map getDbSource(Integer dbSourceId) {

        Map<String, Object> params = new HashMap<>(2);
        params.put("dbSourceId", dbSourceId);
        //获取数据源
//        Map result = postResult(params, FileHelpper.map.get("service.common") + FileHelpper.map.get("meta.selectDbList"));
//        Map result = commonFiegn.selectDbList(params);
        Map result = new HashMap();
        log.info("postResult:{}", result);
        return result;

    }


    private Map getPkColumn(Integer tableId) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("metaTableId", tableId);
        params.put("partOfPrimaryKey",1);
        //获取列集合
//        Map result = postResult(params, FileHelpper.map.get("service.common") + FileHelpper.map.get("meta.selectColumnList"));
//        Map result = commonFiegn.getColumnList(params);
        Map result = new HashMap();
        log.info("postResult:{}", result);
        int code = Integer.parseInt(result.get("code").toString());
        if (code == SUCCESS) {
            List<Map<String, Object>> columnList = (List<Map<String, Object>>) (result.get("data"));
            if (columnList != null && !columnList.isEmpty()) {

            }
        }

        return result;
    }


    /**
     * post请求
     *
     * @param params
     * @param url
     * @return
     */
    private Map postResult(Map<String, Object> params, String url) {
        return RestTemplateUtils.postHttp(restTemplate, url, JSON.toJSONString(params), Map.class);
    }


    /**
     * 查询执行信息
     *
     * @param ids
     * @return
     */
    @Override
    public Map getJobInfo(String ids) {
        Map result = new HashMap();
        Map<String, Object> params = new HashMap<>(1);
        params.put("jobIds", ids);
//        String url = FileHelpper.map.get("service.executionTask") + FileHelpper.map.get("executor.selectJobInfo");
//        Map result = postResult(params, url);
        try{
//            result = executionTaskFeign.jobInfoListByIds(params);
        } catch (Exception e) {
            log.error("=======netflixError:{}========", e.getMessage());
            result = null;
        }
        return result;
    }
}
